var http = require('http');
var fs = require('fs');
var path = require('path');

function handle_request(req, res) {
    if (req.url == '/optionSide/sex') {
        // Api 请求方法
        res.writeHead(200, { 'Content-Type': 'application/json;charset=utf-8' });
        setTimeout(function () {
            res.end(JSON.stringify([{
                name: '男',
                value: '0',
            }, {
                name: '女',
                value: '1'
            }, {
                name: '其他',
                value: '2'
            }]));
        }, 1500);
    } else {
        // 不管是什么请求，对文件的请求的话，应该是针对后缀名进行内容读取发放。
        var index1 = req.url.lastIndexOf(".");
        var index2 = req.url.length;
        var suffix = req.url.substring(index1 + 1, index2);
        if (suffix === 'css') {
            res.writeHead(200, { 'Content-Type': 'text/css' });
            res.end(get_file_content(path.join(__dirname, '../' + req.url)));
        } else if (suffix === 'gif') {
            res.writeHead(200, { 'Content-Type': 'image/gif' });
            res.end(get_file_content(path.join(__dirname, '../' + req.url)));
        } else if (suffix === 'png') {
            res.writeHead(200, { 'Content-Type': 'image/png' });
            res.end(get_file_content(path.join(__dirname, '../' + req.url)));
        } else if (suffix === 'jpg') {
            res.writeHead(200, { 'Content-Type': 'image/jpeg' });
            res.end(get_file_content(path.join(__dirname, '../' + req.url)));
        } else if (suffix === 'js') {
            res.writeHead(200, { 'Content-Type': 'application/x-javascript' });
            res.end(get_file_content(path.join(__dirname, '../' + req.url)));
        } else if (suffix === 'json') {
            res.writeHead(200, { 'Content-Type': 'application/json' });
            res.end(get_file_content(path.join(__dirname, '../' + req.url)));
        } else if (suffix === 'html') {
            res.writeHead(200, { 'Content-Type': 'text/html' });
            res.end(get_file_content(path.join(__dirname, '../' + req.url)));
        } else {
            res.writeHead(200, { 'Content-Type': 'text/html' });
            res.end(get_file_content(path.join(__dirname, '../html/index.html')));
        }
    };
};
function get_file_content(filepath) {
    return fs.readFileSync(filepath);
};
var server = http.createServer(handle_request);
server.listen(8080);